package model;
import gui.Gui;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;


public class Reader {
	public static void main(String[] args) throws FileNotFoundException {
		
		List<String> l = new ArrayList<String>();
		l.add("1.gpx"); l.add("san"); l.add("foooooo");

		List<File> files = getGPXFiles();
		
		Gui g = new Gui(files);
	}
	
	static public List<File> getGPXFiles() {
		List<File> gpxes = new ArrayList<File>();
		FileFilter filter = new FileFilter() {
			public boolean accept(File f) {
				return f.getName().endsWith(".gpx");
			}
		};
		
		File dir = new File(".");
		File[] filenames = dir.listFiles(filter);
		
		for (int i=0; i<filenames.length; ++i) {
			gpxes.add(filenames[i]);
		}
		
		return gpxes;
	}
	
	public void Reader() {
	}
	
	static public List<Point> read(File file) {
		List<Point> list = new ArrayList<Point>();
		
		Scanner scan;
		try {
			scan = new Scanner(file);
		
			String line = scan.nextLine();
			while (!line.contains("<trk>")) {
				line = scan.nextLine();
			}
			String name = scan.nextLine();
			name = name.substring(15, name.length()-24);
			
			String starttime = scan.nextLine();
			starttime = starttime.substring(6, starttime.length()-12);
			
			scan.nextLine();
			line = scan.nextLine();
			
			while (!line.contains("</trkseg>")) {
				double lat, lon, elevation;
				int i, i2;
				
				lat = Double.parseDouble(substr(line, "lat=\"", "\""));
				
				lon = Double.parseDouble(substr(line, "lon=\"", "\""));
			
				elevation = Double.parseDouble(substr(line, "<ele>", "</ele>"));
				
				String time = substr(line, "<time>", "</time>");
				Calendar cal = Calendar.getInstance();
				int year, month, date, hour, min, sec;
				i = 0;
				year = Integer.parseInt(time.substring(i, i+4));
				i += 5;
				month = Integer.parseInt(time.substring(i, i+2));
				i += 3;
				date = Integer.parseInt(time.substring(i, i+2));
				i += 3;
				hour = Integer.parseInt(time.substring(i, i+2));
				i += 3;
				min = Integer.parseInt(time.substring(i, i+2));
				i += 3;			
				sec = Integer.parseInt(time.substring(i, i+2));
				cal.set(year, month, date, hour, min, sec);
				Date d = cal.getTime();
				
				Point p = new Point(lat, lon, elevation, d);
				list.add(p);
				
				line = scan.nextLine();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(list.size() +" points read");
		return list;
	}
	
	static private String substr(String line, String start, String end) {
		int i1, i2;
		
		i1 = line.indexOf(start);
		i1 += start.length();
		i2 = line.indexOf(end, i1);
		
		String out = line.substring(i1, i2);
		return out;
	}

}